<?php

namespace app\common\model;

use think\Model;

class UserMoneyLog extends Model
{

    public $_type = [
        1   =>  '商城消费',
        2   =>  '直推奖',
        3   =>  '间推奖',
        4   =>  '提现',
        5   =>  '提现手续费'
    ];

    public function getTypeAttr($key, $val)
    {
        return $this->_type[$val['type']];
    }

    /**
     * 增加记录同时修改用户余额
     * @param $user_id      用户id
     * @param $money        变动金额
     * @param $type         类型  1消费 2直推 3间推 4提现 5提现手续费
     * @param $des          变动说明
     * @param $is_estimate  是否是预计收益 1是 0否
     * @param $extra        额外信息。存储订单号等信息（json格式）
     * @return array
     */
    public function addData($user_id, $money, $type, $des, $is_estimate, $extra)
    {
        if($money == 0) return ['code' => 1, '变动金额为0，不录入记录'];
        $usersMdl = model('Users');
        $userInfo = $usersMdl->where('user_id', $user_id)->field('user_id, user_money')->find();
        if(empty($userInfo))    return ['code' => 0, '用户不存在'];
        if($money < 0 && $userInfo['user_money'] < abs($money))    return ['code' => 0, '余额不足'];
        $this->startTrans();
        //增加记录
        $res = $this->insertGetId([
            'user_id'       => $user_id,
            'money'         => $money,
            'after_money'   => $money + $userInfo['user_money'],
            'des'           => $des,
            'type'          => $type,
            'is_estimate'   => $is_estimate,
            'extra'         => json_encode($extra),
            'create_time'   => time(),
        ]);
        //如果不是预计收益，用户增加金额
        if($is_estimate == 0){
            //修改金额
            $field = $money > 0 ? 'distribut_money' : 'total_amount';//total_amount:消费累计  distribut_money:分佣累计
            $res1 = $usersMdl->where('user_id', $user_id)->update([
                'user_money' => ['exp', 'user_money + ' . $money],
                $field => ['exp', $field . ' + ' . abs($money)]
            ]);
            if(!$res && !$res1){
                $this->rollback();
                return ['code' => 0, 'msg' => '数据录入失败'];
            }
        }
        $this->commit();
        return ['code' => 1, 'msg' => '操作成功'];

    }

    /**
     * 预计收益修改成实际收益
     * @param $order_sn
     * @return array
     */
    public function editEstimate($order_sn)
    {
        $list = $this->where(['des' => $order_sn])->field('id, user_id, money,is_estimate')->select();
        if(empty($list) || $list[0]['is_estimate'] == 0)
            return ['code' => 0, 'msg' => '操作错误'];

        $usersMdl = model('Users');
        $this->startTrans();
        foreach ($list as $k => $v) {
            //修改金额
            $field = $v['money'] > 0 ? 'distribut_money' : 'total_amount';//total_amount:消费累计  distribut_money:分佣累计
            $res = $usersMdl->where('user_id', $v['user_id'])->update([
                'user_money' => ['exp', 'user_money + ' . $v['money']],
                $field => ['exp', $field  . ' + ' . abs($v['money'])]
            ]);

            //因为中间可能用户的金额有变动，所以要重新更新下 after_money
            $user_money = $usersMdl->where('user_id', $v['user_id'])->value('user_money');
            $res1 = $this->where('id', $v['id'])->update([
                'after_money' => $user_money,
                'is_estimate' => 0
            ]);

            if(!$res && !$res1){
                $this->rollback();
                return ['code' => 0, 'msg' => '操作失败'];
            }
        }
        $this->commit();
        return ['code' => 1, 'msg' => '操作成功'];
    }

    /**
     * @param $where
     * @param int $page
     * @param int $num
     * @param string $order
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getList($where, $page = 1, $num = 10, $order = 'id desc')
    {
        return $this->where($where)->page($page, $num)->order($order)->select();
    }

}